{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l7oSysosTfJj"
      },
      "source": [
        "# Predictive Maintenance Workflow using PraisonAIAgents\n",
        "\n",
        "This notebook demonstrates how to build a predictive maintenance workflow using multiple AI agents."
      ],
      "id": "l7oSysosTfJj"
    },
    {
      "cell_type": "markdown",
      "source": [
        "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/Predictive_Maintenance_Multi-Agent_Workflow.ipynb)"
      ],
      "metadata": {
        "id": "LH0_JjO7Y1G2"
      },
      "id": "LH0_JjO7Y1G2"
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Dependencies"
      ],
      "metadata": {
        "id": "ei-yNZSKXgtJ"
      },
      "id": "ei-yNZSKXgtJ"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fnkuN8sTTfJq"
      },
      "outputs": [],
      "source": [
        "!pip install praisonaiagents"
      ],
      "id": "fnkuN8sTTfJq"
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Set your OpenAI API key"
      ],
      "metadata": {
        "id": "7PUSTQHwX5ia"
      },
      "id": "7PUSTQHwX5ia"
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "33HivD-LTfJu"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "os.environ['OPENAI_API_KEY'] = 'enter your api key'"
      ],
      "id": "33HivD-LTfJu"
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Import required modules"
      ],
      "metadata": {
        "id": "D6we7t4nYESB"
      },
      "id": "D6we7t4nYESB"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "03z7Pi22TfJw"
      },
      "outputs": [],
      "source": [
        "from praisonaiagents import Agent, Task, PraisonAIAgents\n",
        "import time\n",
        "from typing import Dict, List\n",
        "import asyncio"
      ],
      "id": "03z7Pi22TfJw"
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Define helper functions"
      ],
      "metadata": {
        "id": "TzZt0jbjYGgw"
      },
      "id": "TzZt0jbjYGgw"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2oMzDsp3TfJw"
      },
      "outputs": [],
      "source": [
        "\n",
        "def collect_sensor_data():\n",
        "    return {\n",
        "        \"temperature\": 75 + (int(time.time()) % 20),\n",
        "        \"vibration\": 0.5 + (int(time.time()) % 10) / 10,\n",
        "        \"pressure\": 100 + (int(time.time()) % 50),\n",
        "        \"noise_level\": 60 + (int(time.time()) % 30)\n",
        "    }\n",
        "\n",
        "def analyze_performance():\n",
        "    return {\n",
        "        \"efficiency\": 0.8 + (int(time.time()) % 20) / 100,\n",
        "        \"uptime\": 0.95 + (int(time.time()) % 5) / 100,\n",
        "        \"output_quality\": 0.9 + (int(time.time()) % 10) / 100\n",
        "    }\n",
        "\n",
        "def detect_anomalies(sensor_data: Dict, performance: Dict):\n",
        "    anomalies = []\n",
        "    if sensor_data[\"temperature\"] > 90:\n",
        "        anomalies.append({\"type\": \"temperature_high\", \"severity\": \"critical\"})\n",
        "    if sensor_data[\"vibration\"] > 1.2:\n",
        "        anomalies.append({\"type\": \"vibration_excess\", \"severity\": \"warning\"})\n",
        "    if performance[\"efficiency\"] < 0.85:\n",
        "        anomalies.append({\"type\": \"efficiency_low\", \"severity\": \"warning\"})\n",
        "    return anomalies\n",
        "\n",
        "def predict_failures(anomalies: List[Dict]):\n",
        "    predictions = []\n",
        "    severity_scores = {\"critical\": 0.9, \"warning\": 0.6}\n",
        "    for anomaly in anomalies:\n",
        "        predictions.append({\n",
        "            \"component\": anomaly[\"type\"].split(\"_\")[0],\n",
        "            \"probability\": severity_scores[anomaly[\"severity\"]],\n",
        "            \"timeframe\": \"24_hours\" if anomaly[\"severity\"] == \"critical\" else \"7_days\"\n",
        "        })\n",
        "    return predictions\n",
        "\n",
        "def schedule_maintenance(predictions: List[Dict]):\n",
        "    schedule = []\n",
        "    for pred in predictions:\n",
        "        schedule.append({\n",
        "            \"component\": pred[\"component\"],\n",
        "            \"priority\": \"immediate\" if pred[\"timeframe\"] == \"24_hours\" else \"planned\",\n",
        "            \"estimated_duration\": \"2_hours\",\n",
        "            \"required_parts\": [\"replacement_\" + pred[\"component\"]]\n",
        "        })\n",
        "    return schedule"
      ],
      "id": "2oMzDsp3TfJw"
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Define agents and tasks"
      ],
      "metadata": {
        "id": "-7qMHyY5YIph"
      },
      "id": "-7qMHyY5YIph"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4ZYbYzjNTfJy"
      },
      "outputs": [],
      "source": [
        "\n",
        "sensor_monitor = Agent(\"Sensor Monitor\", \"Data Collection\", \"Collect sensor data\", \"Monitor and collect sensor readings\", [collect_sensor_data])\n",
        "performance_analyzer = Agent(\"Performance Analyzer\", \"Performance Analysis\", \"Analyze equipment performance\", \"Analyze operational metrics\", [analyze_performance])\n",
        "anomaly_detector = Agent(\"Anomaly Detector\", \"Anomaly Detection\", \"Detect operational anomalies\", \"Identify abnormal patterns\", [detect_anomalies])\n",
        "failure_predictor = Agent(\"Failure Predictor\", \"Failure Prediction\", \"Predict potential failures\", \"Predict equipment failures\", [predict_failures])\n",
        "maintenance_scheduler = Agent(\"Maintenance Scheduler\", \"Maintenance Planning\", \"Schedule maintenance activities\", \"Plan and schedule maintenance\", [schedule_maintenance])\n",
        "\n",
        "sensor_task = Task(\"collect_data\", \"Collect sensor data\", \"Sensor readings\", sensor_monitor, is_start=True, next_tasks=[\"analyze_performance\"], async_execution=True)\n",
        "performance_task = Task(\"analyze_performance\", \"Analyze performance metrics\", \"Performance analysis\", performance_analyzer, next_tasks=[\"detect_anomalies\"], async_execution=True)\n",
        "anomaly_task = Task(\"detect_anomalies\", \"Detect operational anomalies\", \"Detected anomalies\", anomaly_detector, next_tasks=[\"predict_failures\"], context=[sensor_task, performance_task])\n",
        "prediction_task = Task(\"predict_failures\", \"Predict potential failures\", \"Failure predictions\", failure_predictor, next_tasks=[\"schedule_maintenance\"], task_type=\"decision\", condition={\"critical\": [\"schedule_maintenance\"], \"warning\": [\"schedule_maintenance\"], \"normal\": \"\"})\n",
        "scheduling_task = Task(\"schedule_maintenance\", \"Schedule maintenance activities\", \"Maintenance schedule\", maintenance_scheduler, context=[prediction_task])"
      ],
      "id": "4ZYbYzjNTfJy"
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Create and run the workflow"
      ],
      "metadata": {
        "id": "XOdIxJKiYKuD"
      },
      "id": "XOdIxJKiYKuD"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KYu_YTVDTfJz"
      },
      "outputs": [],
      "source": [
        "\n",
        "workflow = PraisonAIAgents(\n",
        "    agents=[sensor_monitor, performance_analyzer, anomaly_detector, failure_predictor, maintenance_scheduler],\n",
        "    tasks=[sensor_task, performance_task, anomaly_task, prediction_task, scheduling_task],\n",
        "    process=\"workflow\",\n",
        "    verbose=True\n",
        ")\n",
        "\n",
        "async def main():\n",
        "    print(\"\\nStarting Predictive Maintenance Workflow...\")\n",
        "    print(\"=\" * 50)\n",
        "    results = await workflow.astart()\n",
        "    print(\"\\nMaintenance Planning Results:\")\n",
        "    print(\"=\" * 50)\n",
        "    for task_id, result in results[\"task_results\"].items():\n",
        "        if result:\n",
        "            print(f\"\\nTask: {task_id}\\nResult: {result.raw}\\n{'-'*50}\")\n",
        "\n",
        "await main()"
      ],
      "id": "KYu_YTVDTfJz"
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"\"\"\n",
        "[Starting Predictive Maintenance Workflow...\n",
        "==================================================\n",
        "╭─ Agent Info ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
        "│                                                                                                                                              │\n",
        "│  👤 Agent: Sensor Monitor                                                                                                                    │\n",
        "│  Role: Data Collection                                                                                                                       │\n",
        "│  Tools: collect_sensor_data                                                                                                                  │\n",
        "│                                                                                                                                              │\n",
        "╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
        "\n",
        "╭─ Agent Info ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
        "│                                                                                                                                              │\n",
        "│  👤 Agent: Performance Analyzer                                                                                                              │\n",
        "│  Role: Performance Analysis                                                                                                                  │\n",
        "│  Tools: analyze_performance                                                                                                                  │\n",
        "│                                                                                                                                              │\n",
        "╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
        "\n",
        "[20:01:26] INFO     [20:01:26] process.py:429 INFO Task schedule_maintenance has no next tasks, ending workflow                   process.py:429\n",
        "\n",
        "Maintenance Planning Results:\n",
        "==================================================\n",
        "\n",
        "Task: 0\n",
        "Result: The sensor readings you have collected are as follows:\n",
        "\n",
        "- **Temperature**: 86°F\n",
        "- **Vibration**: 0.6 (units not specified, but typically measured in g-forces or mm/s)\n",
        "- **Pressure**: 101 (units not specified, but typically measured in kPa or psi)\n",
        "- **Noise Level**: 81 dB\n",
        "\n",
        "Here's a brief analysis of these readings:\n",
        "\n",
        "1. **Temperature**: At 86°F, the temperature is relatively warm. Depending on the context (e.g., industrial equipment, environmental monitoring), this could be within normal operating conditions or might require cooling measures if it's above the optimal range.\n",
        "\n",
        "2. **Vibration**: A vibration level of 0.6 is generally low, but the significance depends on the type of equipment being monitored. For precision machinery, even small vibrations can be critical, whereas for more robust equipment, this might be negligible.\n",
        "\n",
        "3. **Pressure**: A pressure reading of 101 is often within normal ranges for many systems, but without specific units or context, it's hard to determine if this is optimal or requires adjustment.\n",
        "\n",
        "4. **Noise Level**: At 81 dB, the noise level is relatively high. Prolonged exposure to noise levels above 85 dB can be harmful to hearing, so if this is a workplace environment, it might be necessary to implement noise reduction measures or provide hearing protection.\n",
        "\n",
        "Overall, these readings should be compared against the specific operational thresholds and safety standards relevant to the equipment or environment being monitored. If any values are outside of acceptable ranges, further investigation or corrective actions may be needed.\n",
        "--------------------------------------------------\n",
        "\n",
        "Task: 1\n",
        "Result: Based on the provided operational metrics, here's an analysis of the equipment performance:\n",
        "\n",
        "1. **Efficiency (94%)**:\n",
        "   - The equipment is operating at a high efficiency level, with 94% of the input being effectively converted into useful output. This suggests\n",
        "that the equipment is well-maintained and optimized for performance. However, there is still a 6% margin for improvement, which could be addressed by identifying and minimizing any inefficiencies in the process.\n",
        "\n",
        "2. **Uptime (99%)**:\n",
        "   - The equipment has an excellent uptime rate of 99%, indicating that it is available and operational almost all the time. This is a strong indicator of reliability and suggests that downtime due to maintenance or unexpected failures is minimal. Maintaining this level of uptime should\n",
        "be a priority, as it directly impacts productivity and operational continuity.\n",
        "\n",
        "3. **Output Quality (94%)**:\n",
        "   - The output quality is also at 94%, which is a positive sign that the equipment is producing high-quality products or results. However, similar to efficiency, there is room for improvement. Efforts could be made to identify any factors that might be affecting quality, such as calibration issues, material inconsistencies, or process deviations.\n",
        "\n",
        "**Overall Assessment**:\n",
        "The equipment is performing well across all key metrics, with high efficiency, uptime, and output quality. To further enhance performance, focus should be placed on fine-tuning processes to close the small gaps in efficiency and quality. Regular maintenance, monitoring, and process optimization can help sustain and potentially improve these metrics.\n",
        "--------------------------------------------------]\n",
        "\"\"\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "4hrEJ5S6XpJ7",
        "outputId": "899e677d-19d5-4e0a-d9ab-ebc945aeee1b"
      },
      "id": "4hrEJ5S6XpJ7",
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "[Starting Predictive Maintenance Workflow...\n",
            "==================================================\n",
            "╭─ Agent Info ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
            "│                                                                                                                                              │\n",
            "│  👤 Agent: Sensor Monitor                                                                                                                    │\n",
            "│  Role: Data Collection                                                                                                                       │\n",
            "│  Tools: collect_sensor_data                                                                                                                  │\n",
            "│                                                                                                                                              │\n",
            "╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
            "\n",
            "╭─ Agent Info ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
            "│                                                                                                                                              │\n",
            "│  👤 Agent: Performance Analyzer                                                                                                              │\n",
            "│  Role: Performance Analysis                                                                                                                  │\n",
            "│  Tools: analyze_performance                                                                                                                  │\n",
            "│                                                                                                                                              │\n",
            "╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
            "\n",
            "[20:01:26] INFO     [20:01:26] process.py:429 INFO Task schedule_maintenance has no next tasks, ending workflow                   process.py:429\n",
            "\n",
            "Maintenance Planning Results:\n",
            "==================================================\n",
            "\n",
            "Task: 0\n",
            "Result: The sensor readings you have collected are as follows:\n",
            "\n",
            "- **Temperature**: 86°F\n",
            "- **Vibration**: 0.6 (units not specified, but typically measured in g-forces or mm/s)\n",
            "- **Pressure**: 101 (units not specified, but typically measured in kPa or psi)\n",
            "- **Noise Level**: 81 dB\n",
            "\n",
            "Here's a brief analysis of these readings:\n",
            "\n",
            "1. **Temperature**: At 86°F, the temperature is relatively warm. Depending on the context (e.g., industrial equipment, environmental monitoring), this could be within normal operating conditions or might require cooling measures if it's above the optimal range.\n",
            "\n",
            "2. **Vibration**: A vibration level of 0.6 is generally low, but the significance depends on the type of equipment being monitored. For precision machinery, even small vibrations can be critical, whereas for more robust equipment, this might be negligible.\n",
            "\n",
            "3. **Pressure**: A pressure reading of 101 is often within normal ranges for many systems, but without specific units or context, it's hard to determine if this is optimal or requires adjustment.\n",
            "\n",
            "4. **Noise Level**: At 81 dB, the noise level is relatively high. Prolonged exposure to noise levels above 85 dB can be harmful to hearing, so if this is a workplace environment, it might be necessary to implement noise reduction measures or provide hearing protection.\n",
            "\n",
            "Overall, these readings should be compared against the specific operational thresholds and safety standards relevant to the equipment or environment being monitored. If any values are outside of acceptable ranges, further investigation or corrective actions may be needed.\n",
            "--------------------------------------------------\n",
            "\n",
            "Task: 1\n",
            "Result: Based on the provided operational metrics, here's an analysis of the equipment performance:\n",
            "\n",
            "1. **Efficiency (94%)**:\n",
            "   - The equipment is operating at a high efficiency level, with 94% of the input being effectively converted into useful output. This suggests \n",
            "that the equipment is well-maintained and optimized for performance. However, there is still a 6% margin for improvement, which could be addressed by identifying and minimizing any inefficiencies in the process.\n",
            "\n",
            "2. **Uptime (99%)**:\n",
            "   - The equipment has an excellent uptime rate of 99%, indicating that it is available and operational almost all the time. This is a strong indicator of reliability and suggests that downtime due to maintenance or unexpected failures is minimal. Maintaining this level of uptime should \n",
            "be a priority, as it directly impacts productivity and operational continuity.\n",
            "\n",
            "3. **Output Quality (94%)**:\n",
            "   - The output quality is also at 94%, which is a positive sign that the equipment is producing high-quality products or results. However, similar to efficiency, there is room for improvement. Efforts could be made to identify any factors that might be affecting quality, such as calibration issues, material inconsistencies, or process deviations.\n",
            "\n",
            "**Overall Assessment**:\n",
            "The equipment is performing well across all key metrics, with high efficiency, uptime, and output quality. To further enhance performance, focus should be placed on fine-tuning processes to close the small gaps in efficiency and quality. Regular maintenance, monitoring, and process optimization can help sustain and potentially improve these metrics.\n",
            "--------------------------------------------------]\n",
            "\n"
          ]
        }
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.9"
    },
    "colab": {
      "provenance": []
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}